<?php

class mUsers extends CI_Model {
    
    function mUsers(){
            parent::__construct();
            $this->load->helper('url');
            $this->setVars();
    }
    
    function setVars()
    {
        $this->result = '';
        $this->idnya = 0;
    }
        
    public function create() {
        $data = array(
            'user_name'  => $this->input->post( 'cName', true ),
            'email' => $this->input->post( 'cEmail', true )
        );
        
        $this->db->insert( 't_mtr_user', $data );
		
		$ref_id = $this->db->insert_id();
		$this->mglobal->saveLog('user','create',$ref_id);
        return $ref_id;
    }
    
    public function getById( $id ) {
        #$id = intval( $id );
        
        $query = $this->db->where( 'user_id', $id )->limit( 1 )->get( 't_mtr_user' );
        
        if( $query->num_rows() > 0 ) {
            return $query->row();
        } else {
            return array();
        }
    }
    
    public function getAll() {
        //get all records from users table
		
		$this->db->where(array('istatus'=>1));
        $query = $this->db->get( 't_mtr_user' );
        
        if( $query->num_rows() > 0 ) {
            return $query->result();
        } else {
            return array();
        }
    } //end getAll
    
    public function update() {
        $data = array(
            'user_name' => $this->input->post( 'name', true ),
            'email' => $this->input->post( 'email', true )
        );
        
        $this->db->update( 't_mtr_user', $data, array( 'user_id' => $this->input->post( 'id', true ) ) );
		
		$this->mglobal->saveLog('user','update',$this->input->post('id'));
    }
    
    public function delete( $id ) {
        /*
        * Any non-digit character will be excluded after passing $id
        * from intval function. This is done for security reason.
        */
        $id = intval( $id );
        
        //$this->db->delete( 't_mtr_user', array( 'user_id' => $id ) );
		$this->db->update( 't_mtr_user', array('istatus'=>-5), array( 'user_id' => $id ) );
		
		$this->mglobal->saveLog('user','delete',$id);
    } //end delete
    
    
        ########################################################################
        ####### DATA USER ##############
        ########################################################################
        function saveUser($edituser="")
        {
                $dblokal  = $this->load->database("default", TRUE);
				$name = $this->input->post("name");
				$email = $this->input->post("email");
				$username = $this->input->post("username");
                $olduser = $this->input->post("olduser");
				$nik = $this->input->post("nik");
                $usergroup = $this->input->post("usergroup");
                $reportingto = $this->input->post("reportingto");
				$hape = $this->input->post("hape");
                $istatus= $this->input->post("istatus");
                $must_change_password = $this->input->post("must_change_password");
                
				$data = array("user_name"=>$name,
							"email"=>$email,
							"nik"=>$nik,
							"user_password"=>md5("12345"),
							"user_group_id"=>$usergroup,
							"updated_by"=>$this->session->userdata('username'),
							"mobile_number"=>$hape,
                            "istatus"=>$istatus,
                            "must_change_pwd"=> $must_change_password
                            );

				if($reportingto<>""){
					$data["reporting_to"]=$reportingto;
				}else{
					$data["reporting_to"]=$username;
				}
                if($edituser<>""){ 
                        $un = $edituser;
						// $un = $this->uri->segment(4);
                        $data2 = array( "user_id" =>$username,
                                        "user_name"=>$name,
                                        "email"=>$email,
                                        "nik"=>$nik,
                                        "user_group_id"=>$usergroup,
										"updated_on"=>date("Y-m-d H:i:s"),
										"updated_by"=>$this->session->userdata('username'),
                                        "mobile_number"=>$hape,
                                        "istatus"=>$istatus,
                                        "must_change_pwd"=> $must_change_password,
                                        "last_time_change_password" => date("Y-m-d")
                                        );
                        if($edituser<>""){ $data2['created_by'] = $this->session->userdata('username');}

						if($reportingto<>""){
							$data2["reporting_to"]=$reportingto;
						}
                        $pwd = $this->input->post("password");
                        if($pwd<>""){
                            $data2['user_password'] = md5($pwd);
                        }
                        
                        $repto_sama = $this->mglobal->showdata("user_id","t_mtr_user",array('user_id'=>$edituser,'reporting_to'=>$reportingto),"dblokal");
						
						$dblokal->where(array("user_id"=>$un));
						$dblokal->update("t_mtr_user",$data2);
						$this->mglobal->saveLog('user', "update; reportingto=$reportingto" ,$edituser);
						
                        if($reportingto<>"" && $repto_sama == ""){
							#update t_mtr_territory, hal ini boleh dilakukan karena pengecekan terr ada bawahan sudah dilakukan
							#yang diupdate: parent_id berdasarkan user_id
							//kl update user, cek dia maintenance terr/gak $cek_maintenance
							//kl iya, parent_id-nya diganti jadi p_id reportingto-nya $p_id
							//sesuai dengan user_id yang diedit..
							
							$cek_maintenance = $this->mglobal->showdata("territory_id","t_mtr_territory",array('user_id'=>$edituser),"dblokal");
							if($cek_maintenance <> ""){ // dia maintenance terr
								//ambil p_id reportingto
								#$p_id = $this->mglobal->showdata("territory_id","t_mtr_territory",array('user_id'=>$reportingto),"dblokal");
								//$dblokal->where(array("user_id"=>$edituser));
								$dblokal->query("UPDATE t_mtr_territory SET user_id = NULL WHERE user_id='$edituser'");
							}
						}
				}else{
					//$data["created_by"]=$this->session->userdata('username');
					$data["user_id"]=$username;
					
					$dblokal->insert("t_mtr_user",$data);
					$ref_id = $username;
					$this->mglobal->saveLog('user','create',$ref_id);
				}
        }
        
    function getUserComboStatus() {
        return $this->db->get('v_combo_user_status')->result_array();
    }

    function getUser($id = "", $pid="")
    {    
            $dblokal  = $this->load->database("default", TRUE);
            // $this->db->select('field1, field2');
            // $this->db->select('user_id, user_name, reporting_to, user_group_id');
            if($id<>""){
                if($pid<>""){
                    #if($pid = "pida") $dblokal->where(array("resporting_to"=>$id));
                    if($id== "-"){
                        $dblokal->where("reporting_to = user_id");
                    }else{
                        $dblokal->where("reporting_to != user_id");
                        $dblokal->where(array("reporting_to"=>$id));
                    }
                }else{
                    $dblokal->where(array("user_id"=>$id));
                }
            }
            else{
				$dblokal->where("reporting_to != user_id");
			}
			$dblokal->where("istatus = 1");
			$dblokal->order_by('user_name','ASC');
            $query = $dblokal->get("t_mtr_user");
            if($pid<>""){
                    return $query;
            }else{
                    if( $query->num_rows() > 0 ) {
                            return $query->result();
                    } else {
                            return array();
                    }
            }
	}
        


        function getUserReportingTo($id)
        {
			//input: usergroupid parentid dari groupid
			//diproses mendapatkan  parentid dari groupid
                
				$dblokal  = $this->load->database("default", TRUE);
				
                $pid = $this->mglobal->showdata("parent_id","t_mtr_user_group",array('user_group_id'=>$id),"dblokal");
                #if($pid==0) $pid=1;
                // $sql = "SELECT * from t_mtr_user
                //         WHERE user_group_id = '$pid' AND istatus = 1
                //         UNION 
                //         SELECT * from t_mtr_user
                //         WHERE user_id = '$id' AND istatus = 1
                //         ORDER BY user_names ASC";
                $sql = "SELECT * from t_mtr_user
                        WHERE user_group_id = '$pid' AND istatus = 1
                        ORDER BY user_name ASC";
    //             $dblokal->where(array("user_group_id"=>$pid));
				// $dblokal->order_by("user_name","ASC");
    //             $query = $dblokal->get("t_mtr_user");
                
				//$query = $dblokal->query("SELECT * FROM f_get_reporting_to('$userId') A (usrId VARCHAR(30), usrName TEXT);");
                $query = $dblokal->query($sql);

                if( $query->num_rows() > 0 ) {
                        return $query->result();
                } else {
                        return array();
                }
	}


    // public function getUserReportingTo($user_group_id)
    // {
    //     $this->db->select('user_id, upper(user_name) as "user_name", user_group_id');
    //     $this->db->where('user_group_id', $user_group_id);
    //     $this->db->where('istatus', 1);
    //     $this->db->order_by('user_name', 'asc');
    //     $query = $this->db->get('t_mtr_user');
    //     if( $query->num_rows() > 0 ) {
    //         return $query->result();
    //     } else {
    //         return array();
    //     }
    // }
        
        function deleteUser($id){
			$dblokal  = $this->load->database("default", TRUE);
			$this->db->update( 't_mtr_user', array('istatus'=>0), array( 'user_id' => $id ) );
		
			$this->mglobal->saveLog('user','delete',$id);
		}
    
        function getUserTree($id = "-",$p=0)
        {
                $query = $this->getUser($id,"pid");
                $k=0;  $p++;
                $jum = $query->num_rows();
                $this->idnya ++;
		
				if($query->num_rows()>0){
                        $this->result .='[';
                        foreach($query->result() as $r){
                                $unencoded=$r->user_id;
                                $r->user_id = $this->enc->fogit($r->user_id); // ini diedit cuyyyyy..aseeekkk

								$link="";
								if($r->created_by <> 'ois') {
									$link="<a href='". site_url("/user_management/index/update/". $r->user_id) ."'>update</a>";
								}
								
								$usergroup=$this->mglobal->showdata('user_group_name','t_mtr_user_group',array('user_group_id'=>$r->user_group_id),'dblokal');
								$this->result .='{"id":"'. $r->user_id .'",
                                                "name":"'. $r->user_name .'",
                                                "size":"'. $unencoded .'",
                                                "nik":"'. $r->nik .'",
                                                "emails":"'. $r->email .'",
												"namagroup":"'. $usergroup .'",
												"istatus":"'. ($r->istatus==1?"Aktif":"Non Aktif") .'",
                                                "hapes":"'. $r->mobile_number .'",
                                                "date":"'. $link .'",
												"p":"'. $p .'",
                                                "iconCls":"icon-user-'. $p .'"';
												
								$cek = $this->getUser($r->user_id,"pida");
								if($cek->num_rows() >0){
									$this->result .= ',"state":"closed"';
								}
                                $k++;
								$this->result .='}';
                                if($k!=$jum) $this->result .=',';
                        }
                        $this->result .="]";
                }
                return $this->result;
	}
        
        
        function change_password($id="")
        {
                $dblokal  = $this->load->database("default", TRUE);
		$pwd = $this->input->post("new-password");
		
		$data = array(
          "user_password"             => md5($pwd),
          "must_change_password"      => 0, 
          "last_time_change_password" => date("Y-m-d"),
          "updated_by"                => $this->session->userdata('username'),
          "updated_on"                => date('Y-m-d H:i:s')
        );
		$dblokal->where(array("user_id"=>$id));
		$dblokal->update("t_mtr_user",$data);
        }
        
        ##update login_attemp
        function update_login_attemp($user_id,$jumlah){
                $dblokal  = $this->load->database("default", TRUE);
		
				$data = array("logon_attempt"=>$jumlah);
				$dblokal->where(array("user_id"=>$user_id));
				$dblokal->update("t_mtr_user",$data);
				
				$this->mglobal->saveLog('password','login_attemp',$user_id);
        }
		
		function searchUser($id = "", $name="", $nik="", $group="",$reporting="",$hape="",$email="")
        {    
                $dblokal  = $this->load->database("default", TRUE);
                if($id<>""){
                    $dblokal->like("UPPER(user_id)", strtoupper($id));
				}
				
				if($name<>""){
                    $dblokal->like("UPPER(user_name)", strtoupper($name));
				}
				
				if($nik<>""){
                    $dblokal->like("UPPER(nik)", strtoupper($nik));
				}
				if($group<>""){
                    $dblokal->where("user_group_id", $group);
				}
				if($reporting<>""){
                    $dblokal->where("reporting_to", $reporting);
				}
				if($hape<>""){
                    $dblokal->like("mobile_number", $hape);
				}
				if($email<>""){
                    $dblokal->like("UPPER(email)", strtoupper($email));
				}
				
                $query = $dblokal->get("t_mtr_user");
                
				if( $query->num_rows() > 0 ) {
						return $query->result();
				} else {
						return array();
				}
                
		}
    function mustChangePwd($user_id) {
        $dblokal  = $this->load->database("default", TRUE);
        $this->db->SELECT("must_change_pwd");
        $query = $this->db->get_where("t_mtr_user", array("user_id"=>$user_id));
        return $query->row()->must_change_pwd;
    }

    public function treeGroups($group_id) {
        $dblokal  = $this->load->database("default", TRUE);
        // if ($group_id =='') {
        //     $where = '"user_group_id" = "parent_id"';
        // }
        // else {
        //     $where = '"parent_id" = '.$group_id;
        // }
        // $sql = "SELECT * from t_mtr_user_group where $where ORDER BY user_group_id ASC";
        $sql = "SELECT user_group_id, user_group_name, parent_id from t_mtr_user_group ";

        $query = $dblokal->query($sql)->result_array();

        if ( (is_array ( $query )) && ( count($query) > 0)) {
            foreach ( $query as $object ) {
            $id = $object ['user_group_id'];
            $newData [$id] ['parent_id'] = self::treeGroups($id);
            }
            return $newData;
            }
        }
   public function reset_password($user_id) {
        $data = array(
            "logon_attempt" => 0,
            "user_password" => md5('12345'), 
            "last_time_change_password" => date("Y-m-d"),
            "must_change_password" => 1
            );
        $this->db->where("user_id", $user_id);
        $this->db->update('t_mtr_user', $data); 
        return "12345";
    }
} //end class